package com.micro.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class SvnMsgToDingding {
    public static void main(String[] args) throws Exception {
        String token = "c8a85f0cab9c2af22ed65d83f790d4cdb4baf141d6ee0dc370ea158645760190";
        String content = "提交时间：%tttt% \n提交版本：%REV% \n作者：%AUTHOR%\n提交备注：%MESSAGE%\n修改目录：%CHANGEDDIRS% ";
        content = "{\"msgtype\": \"text\",\"text\": {\"content\": \""+content+"\"}}";
        httpsRequest("https://oapi.dingtalk.com/robot/send?access_token="+token, "POST", content);
        System.out.println("OK");
        System.exit(0);
    }

    public static void sendMsg(String submitTime, long version, String author, String message) {
        String token = "c8a85f0cab9c2af22ed65d83f790d4cdb4baf141d6ee0dc370ea158645760190";
//        String token = "84181fa5f722e70e383cfcff30a8a5a93789dd068e821bf638809077cf509bce";
        String content = "提交时间："+submitTime+" \n提交版本："+version+" \n提交人："+author+"\n提交备注："+message;
        content = "{\"msgtype\": \"text\",\"text\": {\"content\": \""+content+"\"}}";
        System.out.println("content:" + content);
        try {
            httpsRequest("https://oapi.dingtalk.com/robot/send?access_token="+token, "POST", content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送https请求
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) throws Exception {
        HttpsURLConnection conn = null;
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL(requestUrl);
            conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/json");
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(outputStr.getBytes("utf-8"));
                outputStream.close();
            }
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            return buffer.toString();
        } catch (Exception e) {
            throw e;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                }
            }
        }
    }
}